#!/bin/sh

#
# Test the failure conditions of fat_mv
#

. "$(cd "$(dirname "$0")" && pwd)/common.sh"

cat >$CONFIG <<EOF
define(BOOT_PART_OFFSET, 63)
define(BOOT_PART_COUNT, 77238)

file-resource 1K.bin {
	host-path = "${TESTFILE_1K}"
}

task mkfs {
    on-init {
        fat_mkfs(\${BOOT_PART_OFFSET}, \${BOOT_PART_COUNT})
    }
}
task complete {
    on-resource 1K.bin {
        fat_touch(\${BOOT_PART_OFFSET}, "wont_make_it_out_of_cache")
        fat_write(\${BOOT_PART_OFFSET}, "this/will/fail/1k.bin")
    }
    on-error {
        fat_touch(\${BOOT_PART_OFFSET}, "worked")
    }
}
EOF

# Create the firmware file, then "burn it"
$FWUP_CREATE -c -f $CONFIG -o $FWFILE
$FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t mkfs
echo $FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t complete
if $FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t complete; then
    echo "The fat_write should have failed."
    exit 1
fi

EXPECTED_OUTPUT=$WORK/expected.out
ACTUAL_OUTPUT=$WORK/actual.out

cat >$EXPECTED_OUTPUT << EOF
 Volume in drive : has no label
 Volume Serial Number is 0022-2DB6
Directory for ::/

worked             0 1980-01-01   0:00
        1 file                    0 bytes
                         38 910 464 bytes free

EOF

# Check that the directory looks right
mdir -i $WORK/fwup.img@@32256 > $ACTUAL_OUTPUT
diff -w $EXPECTED_OUTPUT $ACTUAL_OUTPUT

# Check the FAT file format using fsck
dd if=$WORK/fwup.img skip=63 of=$WORK/vfat.img
$FSCK_FAT $WORK/vfat.img

# Check that the verify logic works on this file
$FWUP_VERIFY -V -i $FWFILE
